package com.ysd.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.exception.RRException;
import com.ysd.modules.app.dao.*;
import com.ysd.modules.app.entity.*;
import com.ysd.modules.app.service.OptionsRecordsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class OptionsRecordsServiceImpl extends ServiceImpl<OptionsRecordsDao, OptionsRecordsEntity> implements OptionsRecordsService {

    @Resource
    private ChaptersDao chaptersDao;
    @Resource
    private TopicDao topicDao;
    @Resource
    private PracticeResultDao practiceResultDao;
    @Resource
    private TestPapersDao testPapersDao;

    /**
     * 保存选项记录
     *
     * @param ore
     * @return
     */
    @Override
    public boolean save(OptionsRecordsEntity ore) {
        int len = 0;
        if (ore.getStuId() == null || ore.getStuId() == 0 || ore.getTopicId() == null || ore.getTopicId() == 0) {
            throw new RRException("学生id或题目id不能为空");
        }
        /**
         * 根据学生id和题目id查询是否已经做过这道题目
         */
        QueryWrapper<OptionsRecordsEntity> qw = new QueryWrapper<>();
        qw.eq("stu_id", ore.getStuId());
        qw.eq("topic_id", ore.getTopicId());
        qw.eq("paper_id", ore.getPaperId());
        List<OptionsRecordsEntity> optionsRecordsEntityList = baseMapper.selectList(qw);
        /**
         * 如果为空则 为做过这到题目，则添加
         */
        if (optionsRecordsEntityList == null || optionsRecordsEntityList.size() <= 0) {
            len = baseMapper.insert(ore);
        } else {
            /**
             * 否则进行修改
             */
            UpdateWrapper<OptionsRecordsEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("stu_id", ore.getStuId());
            updateWrapper.eq("paper_id", ore.getPaperId());
            updateWrapper.eq("topic_id", ore.getTopicId());
            len = baseMapper.update(ore, updateWrapper);
        }
        if (len > 0) {
            return true;
        }
        return false;
    }

    /**
     * 提交章节练习返回的内容
     *
     * @param targetId
     * @param stuId
     * @return
     */
    @Override
    public PracticeResult getPracticeResult(Integer targetId, Integer stuId, Integer type) {
        if (targetId == null) {
            throw new RRException("章节id不能为空");
        }
        if (stuId == null || stuId == 0) {
            throw new RRException("学生id不能为空");
        }
        PracticeResult practiceResult = new PracticeResult();
        practiceResult.setTargetId(targetId);
        practiceResult.setStuId(stuId);
        practiceResult.setType(type);
        switch (type) {
            case 1:
                /**
                 * 根据paper id查询 试卷信息
                 */
                TestPaper testPaper = testPapersDao.selectById(targetId);
                if (testPaper == null) {
                    throw new RRException("没有找到试卷信息");
                }
                practiceResult.setTitle(testPaper.getTitle());
                break;
            case 2:
                /**
                 * 根据章节id查询章节信息
                 */
                ChapterEntity chapterEntity = chaptersDao.selectById(targetId);
                if (chapterEntity == null) {
                    throw new RRException("没有查询到章节信息");
                }
                practiceResult.setTitle("第" + chapterEntity.getOrderNum() + "章：" + chapterEntity.getName());
                break;
        }
        practiceResult.setCreateTime(new Date());
        /**
         * 根据学生id和章节id查询答题数量
         */
        QueryWrapper<OptionsRecordsEntity> ore = new QueryWrapper<>();
        ore.eq("stu_id", stuId);
        ore.eq("paper_id", targetId);
        int answerNum = baseMapper.selectCount(ore);
        practiceResult.setAnswerNum(answerNum);
        /**
         * 查询答对的数量
         *  比对 topic里边的 answer_id和 options_record里边的 options_id 是否相等
         */
        List<OptionsRecordsEntity> recordsEntityList = baseMapper.selectList(ore);
        int rightNum = 0;
        for (int i = 0; i < recordsEntityList.size(); i++) {
            OptionsRecordsEntity optionsRecordsEntity = recordsEntityList.get(i);
            int tid = optionsRecordsEntity.getTopicId();
            String opts = optionsRecordsEntity.getOptionsId();
            /**
             * 根据tid 查topic 中数据
             */
            TopicEntity topicEntity = topicDao.selectById(tid);
            System.out.println(topicEntity.getAnswerId());
            if (topicEntity.getAnswerId().equals(opts)) {
                rightNum++;
            }
        }
        practiceResult.setRightNum(rightNum);
        practiceResult.setWrongNum(answerNum - rightNum);
        /**
         * 计算正确率
         */
        double res = Double.parseDouble(rightNum + "") / Double.parseDouble(answerNum + "");
        /**
         * 设置小数点后边一位
         */
        DecimalFormat df = new DecimalFormat("#.0");
        String accuracy = res >= 0 ? df.format(res * 100) + "" : "0";
        practiceResult.setAccuracy(accuracy);
        /**
         * 保存记录
         */
        QueryWrapper<PracticeResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("target_id", targetId);
        queryWrapper.eq("stu_id", stuId);
        queryWrapper.eq("type", type);
        List<PracticeResult> results = practiceResultDao.selectList(queryWrapper);
        if (results.size() == 0) {
            int len = practiceResultDao.insert(practiceResult);
            if (len == 0) {
                throw new RRException("操作失败，请联系管理员");
            }
        } else {
            UpdateWrapper<PracticeResult> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("target_id", targetId);
            updateWrapper.eq("stu_id", stuId);
            updateWrapper.eq("type", type);
            int len = practiceResultDao.update(practiceResult, updateWrapper);
            if (len == 0) {
                throw new RRException("操作失败，请联系管理员");
            }
        }
        return practiceResult;
    }

    @Override
    public boolean resetOptionsRecords(Integer tid, Integer stuId) {
        Map<String, Object> map = new HashMap<>();
        map.put("paper_id", tid);
        map.put("stuId", stuId);
        int len = baseMapper.deleteByMap(map);
        if (len > 0) {
            return true;
        }
        return false;
    }

    /**
     * 昨天刷题数量
     *
     * @param stuId
     * @return
     */
    @Override
    public int getYesterdayNum(Integer stuId) {
        /**
         * 获取昨天时间
         */
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
        Map<String, Object> map = new HashMap<>();
        map.put("create_time", yesterday);
        map.put("stu_id", stuId);
        return baseMapper.getYesterdayNum(map);
    }

    /**
     * 做题记录中的一键清空
     *
     * @param stuId
     * @return
     */
    @Override
    public int resetOptionsRecords(Integer stuId) {
        Map<String, Object> map = new HashMap<>();
        map.put("stuId", stuId);
        return baseMapper.deleteByMap(map);
    }

    /**
     * 根据学生ID查询学生做题记录
     *
     * @param stuId
     * @return
     */
    @Override
    public List<PracticeResult> getPracticeResultList(Integer stuId) {
        QueryWrapper<PracticeResult> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_id", stuId);
        return practiceResultDao.selectList(queryWrapper);
    }

    /**
     * 错题集
     *
     * @param stuId
     * @param courseId
     * @return
     */
    @Override
    public Map<String, Object> getWrongTopic(Integer stuId, Integer courseId) {
        Map<String, Object> map = new HashMap<>();
        /**
         * 总错题数量
         */
        Map<String, Object> map1 = new HashMap<>();
        map1.put("stu_id", stuId);
        map1.put("course_id", courseId);
        int wrongSum = baseMapper.getWrongSum(map1);
        map.put("wrongSum", wrongSum);
        /**
         * 错误信息
         */
        List<Map<String, Object>> mapList = baseMapper.getWrongInfo(map1);
        map.put("mapList", mapList);
        return map;
    }

}
